use std::fs::File;
use std::io::{self, Read};
use std::collections::{HashMap, HashSet};

// 定义City结构体
#[derive(Debug)]
struct City {
    name: String,
    neighbors: HashSet<String>, // 使用 HashSet 存储邻居，自动去重
}

// 定义Batch结构体
#[derive(Debug)]
struct Batch {
    name: i32,
    cities: Vec<City>,
}

// 解析 JSON 文件
fn parse_json(file_path: &str) -> io::Result<Vec<Batch>> {
    let mut file = File::open(file_path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    let mut batches = Vec::new();
    let stripped = contents.trim();
    if !stripped.starts_with('{') || !stripped.ends_with('}') {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid JSON format"));
    }

    let json_body = &stripped[1..stripped.len() - 1];
    for batch_entry in json_body.split("},") {
        let parts: Vec<&str> = batch_entry.splitn(2, ':').collect();
        if parts.len() != 2 {
            continue;
        }

        // 解析批次号
        let batch_name_result = parts[0].trim().trim_matches(|c| c == '"' || c == '{').parse::<i32>();
        let batch_name = match batch_name_result {
            Ok(name) => name,
            Err(_) => {
                eprintln!("Error parsing batch number.");
                continue;
            }
        };

        // 解析城市群
        let cities_body = parts[1]
            .trim()
            .trim_end_matches('}')
            .trim_start_matches('{');

        let mut cities = Vec::new();
        for city_entry in cities_body.split("],") {
            let city_parts: Vec<&str> = city_entry.splitn(2, ':').collect();
            if city_parts.len() != 2 {
                continue;
            }
            let city_name = city_parts[0].trim().trim_matches('"');
            let neighbors = city_parts[1]
                .trim()
                .trim_matches(|c| c == '[' || c == ']')
                .split(",")
                .filter_map(|s| {
                    let n = s.trim().trim_matches('"').to_string();
                    if n != city_name { Some(n) } else { None } // 过滤自环
                })
                .collect::<HashSet<String>>();

            cities.push(City {
                name: city_name.to_string(),
                neighbors,
            });
        }

        batches.push(Batch {
            name: batch_name,
            cities,
        });
    }

    Ok(batches)
}

// 计算当前批次包含多少个省份
fn count_provinces_in_batch(cities: &[City]) -> i32 {
    let mut province_count = 0;
    let mut city_map: HashMap<String, i32> = HashMap::new();
    for city in cities {
        if city_map.contains_key(&city.name) {
            // 城市已经在里面了,对邻居们全部标记为同一个省份
            let province_id = city_map[&city.name];
            for neighbor in city.neighbors.iter() {
                city_map.insert(neighbor.clone(), province_id);
            }
        } else {
            // 城市不在里面,新的省份, 判断子元素是否有在里面的
            let mut has_neighbor_in_batch = 0;

            for neighbor in city.neighbors.iter() {
                if let Some(&value) = city_map.get(neighbor) {
                    has_neighbor_in_batch = value; // 提取并赋值给 has_neighbor_in_batch
                    break; // 找到后直接退出循环
                }
            }
            
            if has_neighbor_in_batch != 0 {
                // 邻居在里面, 标记城市为同一个省份
                city_map.insert(city.name.clone(), has_neighbor_in_batch);
                for neighbor in city.neighbors.iter() {
                    city_map.insert(neighbor.clone(), has_neighbor_in_batch);
                }
            } else {
                province_count += 1;
                let province_id = province_count;
                city_map.insert(city.name.clone(), province_id);
                for neighbor in city.neighbors.iter() {
                    city_map.insert(neighbor.clone(), province_id);
                }
            }
        }
    }
    province_count
}

// 计算批次的省份数
pub fn count_provinces() -> String {
    let batches = parse_json("./district.json").unwrap();

    let mut results = Vec::new();

    // 打印解析结果并计算每个批次的省份数
    for batch in &batches {
        let province_count = count_provinces_in_batch(&batch.cities);
        //println!("Batch {}: {} provinces", batch.name, province_count);
        results.push(province_count.to_string());
    }

    results.join(",") // 返回以逗号分隔的省份数量字符串
}
